@echo off
chcp 65001 >nul
echo ========================================
echo Blockchain Stock Exchange System
echo ========================================
echo.

echo [1/5] Checking environment...
where node >nul 2>nul
if %ERRORLEVEL% neq 0 (
    echo [ERROR] Node.js not found, please install Node.js first
    pause
    exit /b 1
)

where java >nul 2>nul
if %ERRORLEVEL% neq 0 (
    echo [ERROR] Java not found, please install JDK 11+
    pause
    exit /b 1
)

where mvn >nul 2>nul
if %ERRORLEVEL% neq 0 (
    echo [ERROR] Maven not found, please install Maven
    pause
    exit /b 1
)

echo [OK] Environment check passed
echo.

echo [2/5] Starting Hardhat local node...
cd blockchain
if not exist node_modules (
    echo First time running, installing dependencies...
    call npm install
)
start "Hardhat Node" cmd /k "npm run node"
echo [OK] Hardhat node starting...
timeout /t 5 /nobreak >nul
echo.

echo [3/5] Deploying smart contract...
call npm run deploy
if %ERRORLEVEL% neq 0 (
    echo [ERROR] Contract deployment failed
    pause
    exit /b 1
)
echo [OK] Contract deployed successfully
echo.

echo [4/5] Starting backend service...
cd ..\backend
start "Backend Service" cmd /k "mvn spring-boot:run"
echo [OK] Backend service starting...
timeout /t 10 /nobreak >nul
echo.

echo [5/5] Starting frontend application...
cd ..\frontend
if not exist node_modules (
    echo First time running, installing dependencies...
    call npm install
)
start "Frontend App" cmd /k "npm run dev"
echo [OK] Frontend application starting...
echo.

echo ========================================
echo System startup complete!
echo ========================================
echo.
echo Please follow these steps:
echo 1. Wait for all services to start (about 30 seconds)
echo 2. Open browser: http://localhost:5173
echo 3. MetaMask connection:
echo    - System will auto-detect and prompt to switch network
echo    - Click "OK" to auto-configure
echo    - Manual config: RPC URL: http://127.0.0.1:8545, Chain ID: 31337
echo 4. Import test account (see Hardhat Node window for private key)
echo.
echo To close all services, close each terminal window
echo ========================================
pause

